package com.irdstudio.apicenter.frame.web;

import java.io.IOException;
import java.sql.Connection;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.sql.DataSource;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.irdstudio.apicenter.frame.core.jdbc.util.ConnectionManager;

/**
 * MACMS 平台MVC入口程序 本类作用： 接收请求，有不同controller进行业务处理，结果有view展现。
 * 
 * @author guangming.li
 * @date 2015-05-20
 */
public class MacmsEntryServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	/* 文本日志记录对象(Logback对象) */
	private final static Logger logger = LoggerFactory
			.getLogger(MacmsEntryServlet.class);

	/* Web交易处理总线 */
	private static MacmsControllerBus mwcBus = null;

	/**
	 * 启动时初始化
	 */
	@Override
	public void init(ServletConfig config) throws ServletException {

		super.init(config);

		// 初始化数据库连接管理器(依据JNDI)
		ApplicationContext ac = WebApplicationContextUtils
				.getRequiredWebApplicationContext(config.getServletContext());
		ConnectionManager.setDataSource((DataSource) ac.getBean("dataSource"));
		Connection conn = ConnectionManager.getConnection();

		try {
			mwcBus = MacmsControllerBusUtil.initializeBusConfigure(conn);
		} catch (MacmsException e) {
			e.printStackTrace();
		} finally {
			// 释放连接资源
			ConnectionManager.releaseConnection(conn);
		}

	}

	/**
	 * 移动应用客户端请求接入处理主方法
	 * 
	 * @param request
	 * @param response
	 * @throws ServletException
	 * @throws IOException
	 */
	protected void processRequest(HttpServletRequest request,
			HttpServletResponse response) {

		response.setContentType("text/html;charset=UTF-8");

		// 截获所有异常，在有异常的情况下默认返回JSON字符串给客户端
		try {

			// 直接获取请求的地址,去掉应用名称(即contextPath)
			String reqURI = request.getRequestURI();
			String contextPath = request.getContextPath();
			String reqStr = reqURI;
			if (reqURI.startsWith(contextPath))
				reqStr = reqURI.substring(contextPath.length());

			int idx = reqStr.lastIndexOf('.');
			if (idx != -1)
				reqStr = reqStr.substring(0, idx);
			if (reqStr.startsWith("/"))
				reqStr = reqStr.substring(1);

			// 将请求交给Web交易控制总线处理
			mwcBus.execute(reqStr, request, response);

		} catch (Exception e) {
			logger.error("Process Error:", e);
			MacmsRenderUtil.renderCustomErrorJsonView("9999", e.getMessage(),
					response);
		}
	}

	/**
	 * Web端请求接入
	 */
	@Override
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}

	/**
	 * Web请求接入
	 */
	@Override
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}
}
